"use strict";

/**
 * @import { WebpackPluginInstance, Compiler } from 'webpack';
 */
/**
 * @implements {WebpackPluginInstance}
 * @webpack-only 仅webpack可用
 * @desc
 * 动态引入插件
 */
class DynamicIncludePlugin {
  /**
   * @param {string} libName
   */
  constructor(libName) {
    this.libName = libName;
  }

  /**
   * @param {Compiler} compiler
   * @returns {void}
   */
  apply(compiler) {
    // 拦截所有模块的构建，给用户配置有机会命中
    compiler.hooks.normalModuleFactory.tap("DynamicIncludePlugin", (nmf) => {
      nmf.hooks.beforeResolve.tap("DynamicIncludePlugin", (resolveData) => {
        if (resolveData.request === this.libName) {
          // 什么都不用改，继续走正常解析流程即可
          // 这一步只是确保库名出现在依赖图里
        }
      });
    });

    // 如果你要在产物里额外注入一个“入口”用到这个库，可以这样做：
    compiler.hooks.make.tapAsync(
      "DynamicIncludePlugin",
      (compilation, callback) => {
        // 向 entry 追加一个虚拟模块
        const dep = new compiler.webpack.dependencies.ModuleDependency(
          "my-generated-module.js",
        );
        compilation.addEntry(
          compilation.compiler.context,
          dep,
          "main", // 或指定 chunk 名
          // @ts-expect-error - be fine
          callback,
        );
      },
    );
  }
}

module.exports = { webpack: DynamicIncludePlugin };
